<template>
    <div class="template-management">
        <el-card>
            <div slot="header" class="card-header">
                <span>模版管理</span>
                <el-button type="primary" @click="handleAdd">新增模版</el-button>
            </div>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="searchForm">
                    <el-form-item label="模版标题">
                        <el-input v-model="searchForm.title" placeholder="请输入模版标题" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="语言">
                        <el-select v-model="searchForm.language" placeholder="请选择语言" clearable style="width: 240px;">
                            <el-option label="英语" value="en"></el-option>
                            <el-option label="西班牙语" value="es"></el-option>
                            <el-option label="葡萄牙语" value="pt-BR"></el-option>
                            <el-option label="土耳其语" value="tr"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getList">搜索</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 表格区域 -->
            <el-table :data="tableData" v-loading="loading" border>
                <el-table-column prop="language" label="语言" align="center" width="100">
                    <template slot-scope="scope">
                        <span>
                            {{
                                {
                                    'en': '英语',
                                    'es': '西班牙语',
                                    'pt-BR': '葡萄牙语',
                                    'tr': '土耳其语'
                                }[scope.row.language] || scope.row.language
                            }}
                        </span>
                    </template>
                </el-table-column>


                <el-table-column label="封面图" width="100" align="center">
                    <template slot-scope="scope">
                        <el-image v-if="scope.row.cover" :src="scope.row.cover"
                            style="width: 50px; height: 50px; border-radius: 4px;" :preview-src-list="[scope.row.cover]"
                            fit="cover" />
                        <span v-else style="color: #999;">-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="title" align="center" label="模版标题" min-width="150"></el-table-column>
                <el-table-column prop="description" align="center" label="模版描述" min-width="200"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="content_title" align="center" label="内部标题" width="150"></el-table-column>
                <el-table-column prop="click_count" label="点击次数" align="center" width="80"></el-table-column>
                <el-table-column prop="usage_count" label="使用次数" align="center" width="80"></el-table-column>
                <el-table-column prop="sort" label="排序" align="center" width="80"></el-table-column>

                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagination.page" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
                </el-pagination>
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="900px" top="5vh">
            <el-form :model="form" :rules="rules" ref="form" label-width="120px" label-position="left">
                <!-- 基本信息配置 -->
                <div class="form-section">
                    <div class="section-title">基本信息</div>
                    <el-row :gutter="20">
                        <el-col :span="12">

                            <el-form-item label="语言" prop="language">
                                <el-select v-model="form.language" placeholder="请选择语言" clearable style="width: 240px;">
                                    <el-option label="英语" value="en"></el-option>
                                    <el-option label="西班牙语" value="es"></el-option>
                                    <el-option label="葡萄牙语" value="pt-BR"></el-option>
                                    <el-option label="土耳其语" value="tr"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="排序">
                                <el-input-number v-model="form.sort" :min="0" placeholder="数字越小排序越靠前"
                                    style="width: 100%"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="模版标题" prop="title">
                                <el-input v-model="form.title" placeholder="请输入模版标题" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="内部标题">
                                <el-input v-model="form.content_title" placeholder="请输入内部标题" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- <el-form-item label="模版封面">
                        <el-input v-model="form.cover" placeholder="请输入封面图片URL" clearable></el-input>
                    </el-form-item> -->
                    <el-form-item label="模版封面" prop="cover">
                        <el-upload class="img-uploader" action="https://pdf.seamobitech.com/node/Museo/upload "
                            :show-file-list="false" :on-success="(res) => handleUploadedFile(res, 'cover')"
                            :before-upload="() => beforeUploadImg('cover')" :accept="'image/*'">
                            <template v-if="!form.cover">
                                <div style="position:relative;width:88px;height:88px;">
                                    <i class="el-icon-plus img-uploader-icon"></i>
                                    <i v-if="uploadLoading.cover" class="el-icon-loading"
                                        style="position:absolute;top:44px;left:24px;font-size:40px;color:#409EFF"></i>
                                </div>
                            </template>
                            <template v-else>
                                <img :src="form.cover" class="img-preview" />
                                <el-button class="img-delete" icon="el-icon-delete" size="mini"
                                    @click="handleDeleteFile('cover', $event)" circle plain type="danger" />
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="模版描述">
                        <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入模版描述"
                            show-word-limit :maxlength="500"></el-input>
                    </el-form-item>
                </div>

                <!-- 问题配置 -->
                <div class="form-section">
                    <div class="section-title">
                        问题配置
                        <span class="section-subtitle">（至少配置一个问题）</span>
                    </div>

                    <div class="question-list">
                        <div v-for="(question, questionIdx) in form.questions_json" :key="questionIdx"
                            class="question-card">
                            <!-- 问题头部 -->
                            <div class="question-header">
                                <span class="question-index">问题 {{ questionIdx + 1 }}</span>
                                <el-button v-if="form.questions_json.length > 1" size="mini" type="text"
                                    icon="el-icon-delete" class="delete-btn" @click="removeQuestion(questionIdx)">
                                    删除问题
                                </el-button>
                            </div>
                            <!-- 问题内容和提示 -->
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="问题内容">
                                        <el-input v-model="question.content" type="textarea" :rows="4"
                                            placeholder="请输入问题内容..." show-word-limit :maxlength="1000"
                                            style="width: 100%"></el-input>
                                    </el-form-item>
                                </el-col>

                            </el-row>
                            <el-row :gutter="20">

                                <el-col :span="24">
                                    <el-form-item label="提示内容">
                                        <el-input v-model="question.tips" type="textarea" :rows="4"
                                            placeholder="请输入提示内容..." show-word-limit :maxlength="500"
                                            style="width: 100%"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                        </div>
                    </div>

                    <!-- 新增问题按钮 -->
                    <div class="add-question-btn">
                        <el-button type="primary" plain icon="el-icon-plus" @click="addQuestion">
                            新增问题
                        </el-button>
                    </div>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitTemplateForm" :loading="submitLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { templateSave, templateList, templatesDelete } from "@/api/museo";

import axios from 'axios'

export default {
    name: "TemplateManagement",
    data() {
        return {
            loading: false,
            tableData: [],
            searchForm: {
                title: '',
                status: ''
            },
            pagination: {
                page: 1,
                pageSize: 10,
                total: 0
            },
            uploadLoading: {
                cover:false
            },
            // 模版表单
            dialogVisible: false,
            dialogTitle: '新增模版',
            submitLoading: false,
            form: {
                id: null,
                title: '',
                cover: '',
                description: '',
                content_title: '',
                weight: 0,
                status: 1,
                questions_json: [
                    {
                        title: '',
                        content: '',
                        tips: '',
                        status: 1
                    }
                ]
            },
            rules: {
                title: [
                    { required: true, message: '请输入模版标题', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        handleUploadedFile(res, field) {
            if (res && res.code === 0 && res.fileUrl) {
                this.form[field] = res.fileUrl;
                this.$message.success('上传成功');

                // 上传成功后触发验证更新
                this.$nextTick(() => {
                    if (this.$refs.form) {
                        this.$refs.form.validateField([field]);
                    }
                });
            } else {
                this.$message.error('上传失败');
            }
        },
        handleDeleteFile(field, event) {
            // 阻止事件冒泡，防止触发上传
            if (event) {
                event.stopPropagation();
                event.preventDefault();
            }

            this.form[field] = '';

            // 删除后触发验证
            this.$nextTick(() => {
                if (this.$refs.form) {
                    this.$refs.form.validateField([field]);
                }
            });
        },
        beforeUploadImg(type) {
            this.uploadLoading[type] = true;
            return true;
        },
        // 1. 新增和编辑都用同一个接口
        async submitTemplateForm() {
            try {
                this.submitLoading = true;
                const payload = {
                    ...this.form,
                    questions_json: this.form.questions_json // 保证 questions 是数组
                };
                // 编辑时需要 id，新增时可不传
                const data = await templateSave(payload);
                if (data.success) {
                    this.$message.success(this.form.id ? '更新成功' : '新增成功');
                    this.dialogVisible = false;
                    this.getList();
                } else {
                    this.$message.error(data.message || '操作失败');
                }
            } catch (error) {
                this.$message.error('操作失败');
            } finally {
                this.submitLoading = false;
            }
        },
        // 获取模版列表
        async getList() {
            try {
                this.loading = true;
                const params = {
                    ...this.searchForm,
                    page: this.pagination.page,
                    pageSize: this.pagination.pageSize
                };
                const data = await templateList(params);
                
                this.tableData = data.list;
                console.log(this.tableData)
                this.pagination.total = data.total;
            } catch (error) {
                this.$message.error('获取数据失败');
            } finally {
                this.loading = false;
            }
        },

        // 重置搜索
        resetSearch() {
            this.searchForm = {
                title: '',
                status: ''
            }
            this.pagination.page = 1
            this.getList()
        },

        // 分页
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.page = 1
            this.getList()
        },
        handleCurrentChange(val) {
            this.pagination.page = val
            this.getList()
        },

        // 新增
        handleAdd() {
            this.dialogTitle = '新增模版'
            this.form = {
                id: null,
                title: '',
                cover: '',
                description: '',
                content_title: '',
                sort: 0,
                status: 1,
                questions_json: [
                    {
                        title: '',
                        content: '',
                        tips: '',
                         
                        status: 1
                    }
                ]
            }
            this.dialogVisible = true
        },

        // 编辑
        async handleEdit(row) {
            this.dialogTitle = '编辑模版'
            this.form = JSON.parse(JSON.stringify(row))
            console.log(this.form)
            this.dialogVisible = true
        },


        // 删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该模版及其所有问题, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const response = await templatesDelete({ id: row.id })
                    if (response.code === 200) {
                        this.$message.success('删除成功')
                        this.getList()
                    } else {
                        this.$message.error(response.data.message || '删除失败')
                    }
                } catch (error) {
                    this.$message.error('删除失败')
                }
            })
        },

        // 复制模版
        async handleCopy(row) {
            this.$prompt('请输入新模版标题', '复制模版', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue: `${row.title} - 副本`,
                inputValidator: (value) => {
                    if (!value || !value.trim()) {
                        return '模版标题不能为空'
                    }
                    return true
                }
            }).then(async ({ value }) => {
                try {
                    const response = await axios.post('/api/templates/copy', {
                        id: row.id,
                        title: value.trim()
                    })
                    if (response.data.code === 200) {
                        this.$message.success('复制成功')
                        this.getList()
                    } else {
                        this.$message.error(response.data.message || '复制失败')
                    }
                } catch (error) {
                    this.$message.error('复制失败')
                }
            })
        },

        // 新增问题
        addQuestion() {
            this.form.questions_json.push({
                title: '',
                content: '',
                tips: '',
                status: 1
            })
        },

        // 删除问题
        removeQuestion(index) {
            if (this.form.questions_json.length > 1) {
                this.form.questions_json.splice(index, 1)
            }
        }
    }
}
</script>

<style scoped>
.template-management {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
}

.pagination-wrapper {
    margin-top: 20px;
    text-align: center;
}

/* 表单分组样式 */
.form-section {
    margin-bottom: 30px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #409EFF;
}

.section-subtitle {
    font-size: 12px;
    color: #909399;
    font-weight: normal;
}

/* 问题卡片样式 */
.question-list {
    margin-bottom: 20px;
}

.question-card {
    border: 1px solid #DCDFE6;
    border-radius: 6px;
    padding: 20px;
    margin-bottom: 15px;
    background-color: #FAFAFA;
    position: relative;
}

.question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #E4E7ED;
}

.question-index {
    font-weight: bold;
    color: #409EFF;
    font-size: 14px;
}

.delete-btn {
    color: #F56C6C;
    padding: 0;
}

.delete-btn:hover {
    color: #F56C6C;
    background-color: transparent;
}

/* 新增按钮样式 */
.add-question-btn {
    text-align: center;
    padding: 20px 0;
    border: 2px dashed #DCDFE6;
    border-radius: 6px;
    background-color: #FAFAFA;
    transition: all 0.3s;
}

.add-question-btn:hover {
    border-color: #409EFF;
    background-color: #F0F9FF;
}

/* 对话框样式调整 */
.el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
}

/* 响应式样式 */
@media (max-width: 768px) {
    .question-card {
        padding: 15px;
    }

    .form-section {
        margin-bottom: 20px;
    }
}
.img-uploader {
    display: inline-block;
    width: 128px;
    height: 128px;
    border: 1.5px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background: #fafbfc;
    text-align: center;
    vertical-align: middle;
}

.img-uploader-icon {
    font-size: 36px;
    color: #aaa;
    line-height: 128px;
    transition: color 0.2s;
}

.img-uploader:hover .img-uploader-icon {
    color: #409EFF;
}

.img-preview {
    width: 128px;
    height: 128px;
    object-fit: cover;
    border-radius: 6px;
    background: #fff;
}

.video-preview {
    width: 128px;
    height: 128px;
    object-fit: contain;
    border-radius: 6px;
    background: #222;
}

.img-delete {
    position: absolute;
    right: 5px;
    top: 5px;
    z-index: 9;
    padding: 0;
    border-radius: 50%;
}
</style>